﻿using System;
using System.Windows.Forms;
using System.IO.Ports;

namespace RFMobile.RF
{
    public sealed class RFConnManager
    {
        /*
         * private object obj;
         * private EventArgs eventArgs;
         */ 

        private Timer t;
        private SerialPort Device;
        private String isml;
        private String isstr;
        private String rfId;

        static readonly RFConnManager instance = new RFConnManager();

        static RFConnManager() { }

        RFConnManager()
        {
            t = new Timer();
            t.Interval = 100;
            t.Tick += new EventHandler(t_Tick);

            Device = new SerialPort("COM8", 9600, Parity.None, 8);
            Device.DataReceived += new SerialDataReceivedEventHandler(Device_DataReceived);
            Device.Open();

            isml = "0200020D020D03";
            SendData();
        }

        public static RFConnManager Instance
        {
            get
            {
                return instance;
            }
        }

        private byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

        private void SendData()
        {
            byte[] data = HexStringToByteArray(isml);
            Device.Write(data, 0, data.Length);
        }

        private void t_Tick(object obj, EventArgs e)
        {
            if (isstr.Length > 12)
            {
                rfId = isstr.Substring(8, 2) + isstr.Substring(6, 2) + isstr.Substring(4, 2) + isstr.Substring(2, 2);
                isstr = "";
            }
        }

        private string ByteArrayToHexString(byte[] data)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            return sb.ToString().ToUpper();
        }

        private void Device_DataReceived(object obj, EventArgs e)
        {
            int bytes = Device.BytesToRead;

            // 创建字节数组
            byte[] buffer = new byte[bytes];

            // 读取缓冲区的数据到数组
            Device.Read(buffer, 0, bytes);
            string data = ByteArrayToHexString(buffer);
            isstr += data;
            isstr = isstr.Replace(" ", "");
            return;
        }

        public String RFID
        {
            get
            {
                return (this.rfId);
            }
        }
    }
}
